package com.qrcode.scan;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.qrcode.scan.camera.CameraView;
import com.qrcode.scan.camera.ImageUtil;
import com.qrcode.scan.camera.OnCaptureData;
import com.qrcode.scan.camera.StatusBarUtil;
import com.qrcode.scan.camera.UIUtil;

import client.PhotoClient;
import client.PhotoSelectResultBean;
import client.osbar.OsBarUtil;
import cn.bingoogolapple.qrcode.core.QRCodeView;

/**
 * 项目名称：com.qrcode.scan
 * 创建人:LuoFG
 * 创建时间:2024/8/26  17:45
 * 描述:
 * 作用:
 */
public class QRActivity extends AppCompatActivity implements QRCodeView.Delegate, View.OnClickListener , OnCaptureData {
    private static final String TAG = QRCodeScanActivity.class.getSimpleName();
    private ScanView mZBarView;
    private View viewPowerZbar, viewBackZbar, viewPhotoZbar, viewLineZbar, viewMapZbar, viewCameraTurn,viewCameraFlashZbar;
    private LinearLayout lineLeftZbar;
    private RelativeLayout barTopZbar;
    private boolean isFlashLight = false;
    private Activity activity;
    private boolean isGetResult = false;
    private TextView btmBtnHint;
    private String[] mTitles = {"扫一扫", "拍照"};
    private SegmentTabLayout segmentTabLayout;
    private RelativeLayout reyScan, reyCamera, reyCameraResult,reyAll,reyBtmGroup;
    private ImageView takePhotoButton,imageCamera,imageCancel,imageOk;
    private CameraView cameraView;
    private LinearLayout lineCameraSet;
    private int mPosition = 0;
    private boolean isQRScanInit=false,isCameraInit=false;
    private int flashFlag=0;
    private String strCameraPath="";//拍照或者图片选择返回的路径
    private String[] mTitlesCamera = { "拍照"};
    private String[] mTitlesScan = { "扫一扫"};

    public static QRCodeLiveEvent<QRCodeResultBean> qrcodeScanResult = new QRCodeLiveEvent<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qr);

        reyAll = findViewById(R.id.rey_all);//全局
        barTopZbar = findViewById(R.id.rey_zbar_top);//顶部区域 暂时无用
        viewBackZbar = findViewById(R.id.view_zbar_back);//返回键
        lineLeftZbar = findViewById(R.id.line_zbar_left);//返回

        mZBarView = findViewById(R.id.zbarView);//扫一扫
        viewPhotoZbar = findViewById(R.id.view_zbar_photo);//相册
        viewPowerZbar = findViewById(R.id.view_zbar_power);//补光
        viewLineZbar = findViewById(R.id.view_zbar_line);//顶部补光
        viewMapZbar = findViewById(R.id.view_zbar_map);//巡检地图
        viewCameraTurn = findViewById(R.id.view_zbar_camera_turn);//摄像头旋转
        viewCameraFlashZbar = findViewById(R.id.view_zbar_camera_flash);//补光灯

        btmBtnHint = findViewById(R.id.btn_btm_hint);//补光提示
        segmentTabLayout = findViewById(R.id.tab_layout);//底部选项卡
        reyScan = findViewById(R.id.rey_scan);//扫一扫view
        reyCamera = findViewById(R.id.rey_camera);//相机拍照
        reyCameraResult = findViewById(R.id.rey_camera_result);//相机结果
        takePhotoButton = findViewById(R.id.take_photo_button);//拍照按钮
        cameraView = findViewById(R.id.cameraView);//拍照预览
        lineCameraSet = findViewById(R.id.line_zbar_camera_set);//拍照相关设置
        imageCamera = findViewById(R.id.imageCamera);//拍照预览

        imageCancel = findViewById(R.id.cancle_save_button);//拍照取消
        imageOk = findViewById(R.id.save_button);//拍照完成
        reyBtmGroup=findViewById(R.id.group_tab);//底部tab
        activity = this;


        initTab();
        init();
        if(QRClient.getClient().getQrType()== QRClient.QRType.ALL){
            reyBtmGroup.setVisibility(View.VISIBLE);
        }
        //相机
        else   if(QRClient.getClient().getQrType()== QRClient.QRType.CAMERA){
            reyBtmGroup.setVisibility(View.GONE);
            setTab(1);
        }
        //扫一扫
        else   if(QRClient.getClient().getQrType()== QRClient.QRType.SCAN){
            reyBtmGroup.setVisibility(View.GONE);
            setTab(0);
        }
    }

    private void initTab() {
        segmentTabLayout.setTabData(mTitles);
        segmentTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                setTab(position);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
    }

    private void setTab(int tab) {
        mPosition = tab;
        segmentTabLayout.setCurrentTab(tab);
        try {
            //扫一扫
            if (tab == 0) {
                reyScan.setVisibility(View.VISIBLE);
                reyCamera.setVisibility(View.GONE);
                viewPhotoZbar.setVisibility(View.GONE);
                viewLineZbar.setVisibility(View.VISIBLE);
                viewMapZbar.setVisibility(View.VISIBLE);
                lineCameraSet.setVisibility(View.GONE);
                imageCamera.setVisibility(View.GONE);
                reyCameraResult.setVisibility(View.GONE);
                if(cameraView!=null&&isCameraInit){
                    cameraView.stopPreview();
                }
                //需要切换前置摄像头
                initZbar();
                if(mZBarView!=null) {
                    //Zbar
                    mZBarView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
                    //mZXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
                    mZBarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
                }
            }
            //拍照
            else {
                reyScan.setVisibility(View.GONE);
                reyCamera.setVisibility(View.VISIBLE);
                if(QRClient.getClient().isOpenPhoto()) {
                    viewPhotoZbar.setVisibility(View.VISIBLE);
                }else{
                    viewPhotoZbar.setVisibility(View.GONE);
                }
                viewLineZbar.setVisibility(View.GONE);
                viewMapZbar.setVisibility(View.GONE);
                lineCameraSet.setVisibility(View.VISIBLE);
                imageCamera.setVisibility(View.GONE);
                reyCameraResult.setVisibility(View.GONE);
                //默认需要切换前置摄像头
                if(mZBarView!=null&&isQRScanInit) {
                    mZBarView.stopCamera(); // 打开后置摄像头开始预览
                }
                initCamera();
                setFlashFlag();
            }
        } catch (Exception e) {
            e.printStackTrace();
            finish();
        }
    }

    private void init() {
        try {
            lineLeftZbar.setOnClickListener(this);
            if (QRClient.getClient().isToOsBar()) {
                StatusBarUtil.setGradientColor(this, reyAll);
            }
            viewBackZbar.setBackgroundResource(QRClient.getClient().getImgBack());


            //其他设置
            viewPhotoZbar.setOnClickListener(this);

            viewPowerZbar.setOnClickListener(this);
            viewLineZbar.setOnClickListener(this);
            viewMapZbar.setOnClickListener(this);
            viewCameraTurn.setOnClickListener(this);
            takePhotoButton.setOnClickListener(this);
            viewCameraFlashZbar.setOnClickListener(this);
            imageCancel.setOnClickListener(this);
            imageOk.setOnClickListener(this);

            setTab(0);
            setPhotoImage();

            QRClient.getClient().setCameraReset(new QRClient.CameraReset() {
                @Override
                public void back() {
                    try {
                        UIUtil.deleteFile(strCameraPath);
                        imageCamera.setVisibility(View.GONE);
                        reyCameraResult.setVisibility(View.GONE);
                        lineCameraSet.setVisibility(View.VISIBLE);
                        if(QRClient.getClient().isOpenPhoto()) {
                            viewPhotoZbar.setVisibility(View.VISIBLE);
                        }

                        if(cameraView!=null){
                            cameraView.resetSwitchCamera();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "init Exception:" + e.getMessage());
        }
        Log.e(TAG, "init finish 1");
    }

    /**
     * 设置扫一扫
     */
    private void initZbar() {
        if(!isQRScanInit) {
            //设置扫描
            mZBarView.getScanBoxView().setQRCodeTipText(QRClient.getClient().getScanTipText());

            mZBarView.getScanBoxView().setCornerColor(QRClient.getClient().getScanCornerColor());
            mZBarView.getScanBoxView().setBorderColor(QRClient.getClient().getScanBorderColor());
            mZBarView.getScanBoxView().setScanLineColor(QRClient.getClient().getScanLineColor());
            mZBarView.getScanBoxView().setTipTextColor(QRClient.getClient().getScanTipTextColor());
            mZBarView.getScanBoxView().setIsBarcode(QRClient.getClient().isBarcode());
            mZBarView.getScanBoxView().setAutoZoom(QRClient.getClient().isAutoZoom());

            mZBarView.setDelegate(this);
            isQRScanInit=true;
        }
    }

    /**
     * 设置拍照
     */
    private void initCamera() {
        if(!isCameraInit){
            cameraView.initCamera();
            //cameraView.reStartCamera();
            isCameraInit=true;
        }else{
            if(cameraView!=null){
                cameraView.resetSwitchCamera();
            }
        }

    }


    private void doResult(String result) {
        if (!isGetResult) {
            isGetResult = true;
            if (qrcodeScanResult.hasObservers()) {
                qrcodeScanResult.postValue(new QRCodeResultBean(QRClient.getClient().getScanTag(), result));
            }
            finish();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e(TAG, "onStart 调用识别");
        if (mPosition == 0) {
            if(mZBarView!=null) {
                //Zbar
                mZBarView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
                //mZXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
                mZBarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
            }
        } else {
            //默认需要切换前置摄像头
            if(mZBarView!=null&&isQRScanInit) {
                mZBarView.stopCamera(); // 打开后置摄像头开始预览
            }
            initCamera();
            setFlashFlag();
        }
    }

    @Override
    protected void onStop() {
        try {
            if(mPosition==0) {
                mZBarView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
            }else{
                cameraView.stopPreview();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        try {
            if(mPosition==0) {
                mZBarView.onDestroy(); // 销毁二维码扫描控件
            }else{
                cameraView.stopPreview();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.e(TAG, "Zbar result:" + result);
        doResult(result);
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        String tipText = mZBarView.getScanBoxView().getTipText();
        String ambientBrightnessTip = "\n\n环境过暗，请打开闪光灯";
        Log.e("zabar环境检测", String.valueOf(isDark));
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                mZBarView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
                viewPowerZbar.setVisibility(View.VISIBLE);
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                mZBarView.getScanBoxView().setTipText(tipText);
                //如果闪光灯未开的情况亮度恢复  则取消掉手电筒显示
            }

            if (!isFlashLight) {
                viewPowerZbar.setVisibility(View.INVISIBLE);
            }
        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Log.e(TAG, "打开相机出错");
    }


    @Override
    public void onClick(View v) {
        try {
            int id = v.getId();
            //闪光灯
            if (id == R.id.view_zbar_power) {
                if (!isFlashLight) {
                    mZBarView.openFlashlight();
                    isFlashLight = true;
                } else {
                    mZBarView.closeFlashlight();
                    isFlashLight = false;
                }
            }
            //闪光灯
            else if (id == R.id.view_zbar_line) {
                if (!isFlashLight) {
                    mZBarView.openFlashlight();
                    isFlashLight = true;
                } else {
                    mZBarView.closeFlashlight();
                    isFlashLight = false;
                }
            }
            //返回键
            else if (id == R.id.line_zbar_left) {
                finish();
            }
            //相册
            else if (id == R.id.view_zbar_photo) {
                if (QRClient.getClient().getPhotoOnClickListen() != null) {
                    QRClient.getClient().getPhotoOnClickListen().onClick(this);
                }
            }
            //巡检地图
            else if (id == R.id.view_zbar_map) {
                finish();
                if (QRClient.getClient().getInspectionOnClickListen() != null) {
                    QRClient.getClient().getInspectionOnClickListen().onClick();
                }
            }
            //相机前后置切换
            else if (id == R.id.view_zbar_camera_turn) {
               if(cameraView!=null){
                   cameraView.switchCamera();
               }
            }
            //拍照
            else if (id == R.id.take_photo_button) {
                if(cameraView!=null){
                    cameraView.takePicture(this);
                }
            }
            //补光灯
            else if (id == R.id.view_zbar_camera_flash) {
                flashFlag++;
                setFlashFlag();
            }
            //取消
            else if (id == R.id.cancle_save_button) {
                try {
                    UIUtil.deleteFile(strCameraPath);
                    imageCamera.setVisibility(View.GONE);
                    reyCameraResult.setVisibility(View.GONE);
                    lineCameraSet.setVisibility(View.VISIBLE);
                    if(QRClient.getClient().isOpenPhoto()) {
                        viewPhotoZbar.setVisibility(View.VISIBLE);
                    }

                    if(cameraView!=null){
                        cameraView.resetSwitchCamera();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //确定
            else if (id == R.id.save_button) {
                if(QRClient.getClient().getTakePhotoResult()!=null) {
                    QRClient.getClient().getTakePhotoResult().back(strCameraPath);
                }
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 设置闪光灯
     */
    private void setFlashFlag(){
        try {
            cameraView.switchFlash(flashFlag);
            if (flashFlag % 3 == 0) {
                viewCameraFlashZbar.setBackgroundResource(R.mipmap.flash_a);
            } else if (flashFlag % 3 == 1) {
                viewCameraFlashZbar.setBackgroundResource(R.mipmap.flash_on);
            } else {
                viewCameraFlashZbar.setBackgroundResource(R.mipmap.flash_off);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 调用相册
     */
    private void setPhotoImage() {
        QRClient.getClient().setPhotoResult(new QRClient.PhotoResult() {
            @Override
            public void back(String path) {
                Log.e("setPhotoImage 拍照返回的结果","path:"+path);
                //showResultImage(path);
                try {
                    if(QRClient.getClient().getTakePhotoResult()!=null) {
                        QRClient.getClient().getTakePhotoResult().back(path);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    public void onCapture(boolean success, String path) {
        if (success) {
            Log.e("onCapture 拍照返回的结果","path:"+path);
            //showResultImage(path);
            try {
                if(QRClient.getClient().getTakePhotoResult()!=null) {
                    QRClient.getClient().getTakePhotoResult().back(path);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(this, "拍照异常", Toast.LENGTH_SHORT).show();
        }
    }


   /* private void showResultImage(String path){
        try {
            strCameraPath=path;
            ImageUtil.drawTextTo(activity, path, QRClient.getClient().getStrWaterMark(), path);
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            imageCamera.setVisibility(View.VISIBLE);
            imageCamera.setImageBitmap(bitmap);

            lineCameraSet.setVisibility(View.GONE);
            reyCameraResult.setVisibility(View.VISIBLE);
            viewPhotoZbar.setVisibility(View.GONE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}